package ua.pp.pycb6a.seposition.analysis;

import static ua.pp.pycb6a.seposition.helper.LoggerHelper.getLogger;
import static ua.pp.pycb6a.seposition.helper.PageContentHelper.encodeUri;
import static ua.pp.pycb6a.seposition.helper.PageContentHelper.getNode;
import static ua.pp.pycb6a.seposition.helper.PageContentHelper.getPageContent;
import static ua.pp.pycb6a.seposition.helper.PropertyHelper.getKeywords;
import static ua.pp.pycb6a.seposition.helper.PropertyHelper.getWebAddress;
import static ua.pp.pycb6a.seposition.helper.WriterHelper.getWriter;
import static ua.pp.pycb6a.seposition.helper.WriterHelper.writeAnalysisResult;
import static ua.pp.pycb6a.seposition.helper.WriterHelper.writeTitle;

public class YandexAnalysis {

    private static final String SEARCH_ENGINE = "http://www.yandex.ru";
    private int position = 0;
    private String uri;

    private String xpathLink = ".//a[@class='b-serp-item__title-link'][contains(@href, '"
            + getWebAddress() + "')]";

    private String xpathCount = ".//a[@class='b-serp-item__title-link'][contains(@href, '"
            + getWebAddress() + "')]/preceding-sibling::b";

    private String xpathButtonNext = ".//a[contains(@class, 'b-pager__next')]";

    public void analyse() {

        writeTitle(SEARCH_ENGINE);

        for (String keyword : getKeywords()) {

            getWriter().print("\nREQUEST: " + keyword);
            getLogger().info("REQUEST: " + keyword);

            search(keyword);
            writeAnalysisResult(position, uri);
            position = 0;
        }
    }

    private void search(String keyword) {

        int page = 0;

        do {
            getPageContent(encodeUri(SEARCH_ENGINE + "/yandsearch?p=" + page
                    + "&text=" + keyword));

            if (getNode(xpathLink) != null) {

                position = Integer.parseInt(getNode(xpathCount)
                        .getTextContent());

                uri = getNode(xpathLink + "/@href").getTextContent();
                break;
            }

            else if (getNode(xpathButtonNext) != null) {
                page++;
            }

        } while (getNode(xpathButtonNext) != null);

    }
}
